///
/// 数字输入框组件
/// 参照Element UI的InputNumber控件实现

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/elegance_theme.dart';
import '../../core/elegance_base.dart';
import 'e_input.dart';

/// 控制按钮位置枚举
enum EInputNumberControlsPosition {
  /// 右侧
  right,
}

/// 数字输入框组件
class EInputNumber extends StatefulWidget {
  /// 创建EInputNumber组件
  const EInputNumber({
    super.key,
    this.value,
    this.onChange,
    this.min = double.negativeInfinity,
    this.max = double.infinity,
    this.step = 1.0,
    this.stepStrictly = false,
    this.precision,
    this.size = EInputSize.normal,
    this.disabled = false,
    this.controls = true,
    this.controlsPosition = EInputNumberControlsPosition.right,
    this.placeholder,
    this.label,
    this.readonly = false,
  });

  /// 绑定值
  final double? value;
  
  /// 值改变时的回调
  final ValueChanged<double>? onChange;
  
  /// 最小值
  final double min;
  
  /// 最大值
  final double max;
  
  /// 步数
  final double step;
  
  /// 是否只能输入 step 的倍数
  final bool stepStrictly;
  
  /// 数值精度
  final int? precision;
  
  /// 尺寸
  final EInputSize size;
  
  /// 是否禁用
  final bool disabled;
  
  /// 是否使用控制按钮
  final bool controls;
  
  /// 控制按钮位置
  final EInputNumberControlsPosition controlsPosition;
  
  /// 占位符
  final String? placeholder;
  
  /// 输入框关联的label文字
  final String? label;
  
  /// 是否只读
  final bool readonly;

  @override
  State<EInputNumber> createState() => _EInputNumberState();
}

class _EInputNumberState extends State<EInputNumber> {
  // 输入框控制器
  late TextEditingController _controller;
  // 焦点节点
  late FocusNode _focusNode;
  // 临时存储的值
  String? _tempValue;
  // 是否获得焦点
  bool _hasFocus = false;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: _formatValue(widget.value));
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      setState(() {
        _hasFocus = _focusNode.hasFocus;
      });
    });
  }

  @override
  void didUpdateWidget(EInputNumber oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果外部value变化且当前没有焦点，则更新控制器的值
    if (oldWidget.value != widget.value && !_hasFocus) {
      _controller.text = _formatValue(widget.value);
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  // 格式化数值显示
  String _formatValue(double? value) {
    if (value == null) {
      return '';
    }
    
    // 根据精度格式化数值
    if (widget.precision != null) {
      return value.toStringAsFixed(widget.precision!);
    }
    
    // 如果是整数，不显示小数点
    if (value % 1 == 0) {
      return value.toInt().toString();
    }
    
    return value.toString();
  }

  // 解析输入的文本为数值
  double? _parseValue(String text) {
    if (text.isEmpty) {
      return null;
    }
    
    return double.tryParse(text);
  }

  // 处理输入变化
  void _handleInputChange(String text) {
    _tempValue = text;
    // 只在输入有效数字时通知外部
    final double? value = _parseValue(text);
    if (value != null && widget.onChange != null) {
      widget.onChange!(value);
    }
  }

  // 处理失去焦点
  void _handleBlur() {
    // 确保值在范围内
    final double? value = _parseValue(_controller.text);
    if (value == null) {
      _controller.text = _formatValue(widget.value);
    } else {
      _updateValue(value);
    }
  }

  // 更新值并确保在范围内
  void _updateValue(double value) {
    // 限制在min和max之间
    double newValue = value.clamp(widget.min, widget.max);
    
    // 如果启用了严格步数，调整到最近的步数倍数
    if (widget.stepStrictly && widget.step != 0) {
      final double remainder = newValue % widget.step;
      if (remainder.abs() > widget.step / 2) {
        newValue = remainder > 0 ? newValue - remainder + widget.step : newValue - remainder;
      } else {
        newValue = newValue - remainder;
      }
    }
    
    // 设置精度
    if (widget.precision != null) {
      newValue = double.parse(newValue.toStringAsFixed(widget.precision!));
    }
    
    // 更新控制器文本
    _controller.text = _formatValue(newValue);
    
    // 通知外部
    if (widget.onChange != null) {
      widget.onChange!(newValue);
    }
  }

  // 增加数值
  void _handleIncrement() {
    if (widget.disabled || widget.readonly) return;
    
    final double currentValue = widget.value ?? 0;
    if (currentValue >= widget.max) return;
    
    _updateValue(currentValue + widget.step);
  }

  // 减少数值
  void _handleDecrement() {
    if (widget.disabled || widget.readonly) return;
    
    final double currentValue = widget.value ?? 0;
    if (currentValue <= widget.min) return;
    
    _updateValue(currentValue - widget.step);
  }

  // 获取输入框的尺寸样式
  InputDecorationTheme _getInputTheme() {
    final EleganceThemeData theme = EleganceTheme.of(context);
    
    double height;
    TextStyle textStyle;
    
    switch (widget.size) {
      case EInputSize.small:
        height = 32;
        textStyle = theme.textStyleSmall;
        break;
      case EInputSize.large:
        height = 40;
        textStyle = theme.textStyleLarge;
        break;
      default:
        height = 36;
        textStyle = theme.textStyle;
    }
    
    return InputDecorationTheme(
      contentPadding: EdgeInsets.symmetric(horizontal: 12),
      isDense: true,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(theme.borderRadius),
        borderSide: BorderSide(
          color: _hasFocus ? theme.primaryColor : theme.borderColor,
          width: theme.borderWidth,
        ),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(theme.borderRadius),
        borderSide: BorderSide(
          color: theme.primaryColor,
          width: theme.borderWidthThick,
        ),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(theme.borderRadius),
        borderSide: BorderSide(
          color: theme.borderColor,
          width: theme.borderWidth,
        ),
      ),
      disabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(theme.borderRadius),
        borderSide: BorderSide(
          color: theme.borderColor,
          width: theme.borderWidth,
        ),
      ),
      hintStyle: TextStyle(
        color: theme.textPlaceholderColor,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final EleganceThemeData theme = EleganceTheme.of(context);
    final InputDecorationTheme inputTheme = _getInputTheme();
    
    // 创建输入框
    Widget input = TextField(
      controller: _controller,
      focusNode: _focusNode,
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r'^-?\d*\.?\d*')),
      ],
      onChanged: _handleInputChange,
      onSubmitted: (_) => _handleBlur(),
      enabled: !widget.disabled,
      readOnly: widget.readonly,
      decoration: InputDecoration(
        hintText: widget.placeholder,
        border: inputTheme.border,
        focusedBorder: inputTheme.focusedBorder,
        enabledBorder: inputTheme.enabledBorder,
        disabledBorder: inputTheme.disabledBorder,
        hintStyle: inputTheme.hintStyle,
        contentPadding: EdgeInsets.symmetric(horizontal: 12),
        isDense: true,
      ),
    );
    
    // 如果需要显示控制按钮
    if (widget.controls && !widget.disabled && !widget.readonly) {
      final Widget controls = _buildControls();
      
      // 根据控制按钮位置组合UI
      switch (widget.controlsPosition) {
        case EInputNumberControlsPosition.right:
          input = Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Expanded(child: input),
              SizedBox(width: 4),
              controls,
            ],
          );
          break;
      }
    }
    
    // 如果有标签，添加标签
    if (widget.label != null) {
      input = Row(
        children: [
          Text(widget.label!),
          SizedBox(width: 8),
          Expanded(child: input),
        ],
      );
    }
    
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(theme.borderRadius),
      ),
      child: input,
    );
  }

  // 构建控制按钮
  Widget _buildControls() {
    final EleganceThemeData theme = EleganceTheme.of(context);
    
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 增加按钮
        InkWell(
          onTap: _handleIncrement,
          child: Container(
            width: 20,
            height: 18,
            decoration: BoxDecoration(
              border: Border.all(
                color: theme.borderColor,
                width: 0.5,
              ),
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(theme.borderRadius),
              ),
              color: theme.surfaceColor,
            ),
            child: Center(
              child: Icon(
                Icons.add,
                size: 10,
                color: widget.value != null && widget.value! >= widget.max ? theme.textPlaceholderColor : theme.textPrimaryColor,
              ),
            ),
          ),
        ),
        // 减少按钮
        InkWell(
          onTap: _handleDecrement,
          child: Container(
            width: 20,
            height: 18,
            decoration: BoxDecoration(
              border: Border.all(
                color: theme.borderColor,
                width: 0.5,
              ),
              borderRadius: BorderRadius.only(
                bottomRight: Radius.circular(theme.borderRadius),
              ),
              color: theme.surfaceColor,
            ),
            child: Center(
              child: Icon(
                Icons.remove,
                size: 10,
                color: widget.value != null && widget.value! <= widget.min ? theme.textPlaceholderColor : theme.textPrimaryColor,
              ),
            ),
          ),
        ),
      ],
    );
  }
}